﻿using System;
using System.Collections.ObjectModel;
using System.Threading.Tasks;
using System.Linq;
using System.Windows.Media;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using Microsoft.Extensions.Logging;
using RotovapPlatform.Domain.Common;
using RotovapPlatform.Domain.Equipment.Device.OilBath.Dto;
using RotovapPlatform.Domain.Equipment.Device.TCU.Dto;
using RotovapPlatform.Domain.Equipment.Device.TemperatureCollector.Dto;
using RotovapPlatform.Domain.Equipment.Device.Valves.Dto;
using RotovapPlatform.Domain.Equipment.Interfaces.Base;
using RotovapPlatform.Domain.Equipment.Interfaces.Services;
using RotovapPlatform.Domain.Equipment.Interfaces.Communication;

namespace RotovapPlatform.UI.ViewModels.DeviceMaintenance.ManualOperation
{
	/// <summary>
	/// 串口设备列表视图模型
	/// </summary>
	public partial class SerialDevicesListViewModel : ObservableObject, IDisposable
	{
		private readonly ILogger<SerialDevicesListViewModel> _logger;
		private readonly IDeviceManager _deviceManager;
		private readonly IDeviceStatusService _deviceStatusService;
		private readonly ISerialServerManager _serialServerManager;
		private bool _disposed;

		#region 属性

		// TCU设备列表
		[ObservableProperty]
		private ObservableCollection<ITCUBase> _tcuList = new();

		// 选中的TCU设备
		[ObservableProperty]
		private ITCUBase _selectedTCU;

		// TCU状态
		[ObservableProperty]
		private TCUStatus _tcuStatus = new();

		// TCU连接状态
		[ObservableProperty]
		private bool _isTcuConnected;

		// 油浴锅设备列表
		[ObservableProperty]
		private ObservableCollection<IOilBathBase> _oilBathList = new();

		// 选中的油浴锅设备
		[ObservableProperty]
		private IOilBathBase _selectedOilBath;

		// 油浴锅状态
		[ObservableProperty]
		private OilBathStatus _oilBathStatus = new();

		// 油浴锅连接状态
		[ObservableProperty]
		private bool _isOilBathConnected;

		// 温度采集模块列表
		[ObservableProperty]
		private ObservableCollection<ITemperatureCollectorBase> _temperatureCollectorList = new();

		// 选中的温度采集模块
		[ObservableProperty]
		private ITemperatureCollectorBase _selectedTemperatureCollector;

		// 温度采集模块状态
		[ObservableProperty]
		private TemperatureCollectorStatus _temperatureCollectorStatus = new();

		// 温度采集模块连接状态
		[ObservableProperty]
		private bool _isTemperatureCollectorConnected;

		// 切换阀列表
		[ObservableProperty]
		private ObservableCollection<IValveBase> _valveList = new();

		// 选中的切换阀
		[ObservableProperty]
		private IValveBase _selectedValve;

		// 切换阀状态
		[ObservableProperty]
		private ValveStatus _valveStatus = new();

		// 切换阀连接状态
		[ObservableProperty]
		private bool _isValveConnected;

		// 切换阀目标通道
		[ObservableProperty]
		private int _targetValveChannel;

		// TCU操作参数
		[ObservableProperty]
		private double _tcuSetTemperature = 25.0;

		[ObservableProperty]
		private bool _tcuPowerSwitch;

		// 油浴锅设置温度
		[ObservableProperty]
		private double _oilBathSetTemperature = 25.0;

		// 油浴锅运行状态
		[ObservableProperty]
		private int _oilBathRunningStatus;

		// 操作结果信息
		[ObservableProperty]
		private string _operationMessage;

		[ObservableProperty]
		private bool _isOperationSuccess;

		[ObservableProperty]
		[NotifyPropertyChangedFor(nameof(IsNotBusy))]
		private bool _isBusy;

		[ObservableProperty]
		private Brush _resultMessageColor = Brushes.Black;

		[ObservableProperty]
		private string _valveCurrentChannel = "未知";

		/// <summary>
		/// 是否不忙，用于UI绑定
		/// </summary>
		public bool IsNotBusy => !IsBusy;

		#endregion

		/// <summary>
		/// 构造函数
		/// </summary>
		public SerialDevicesListViewModel(
			ILogger<SerialDevicesListViewModel> logger,
			IDeviceManager deviceManager,
			IDeviceStatusService deviceStatusService,
			ISerialServerManager serialServerManager)
		{
			_logger = logger;
			_deviceManager = deviceManager;
			_deviceStatusService = deviceStatusService;
			_serialServerManager = serialServerManager;

			// 注册设备状态变化事件
			_deviceStatusService.DeviceStatusChanged += OnDeviceStatusChanged;

			// 初始化加载设备列表
			_ = LoadAllDevicesAsync();

			// 启动连接状态监控
			_ = StartConnectionMonitoringAsync();
		}

		/// <summary>
		/// 重新初始化视图模型，用于页面重新加载时刷新数据
		/// </summary>
		public void Reinitialize()
		{
			_logger?.LogInformation("重新初始化串口设备列表视图模型");

			// 确保事件处理程序只注册一次
			_deviceStatusService.DeviceStatusChanged -= OnDeviceStatusChanged;
			_deviceStatusService.DeviceStatusChanged += OnDeviceStatusChanged;

			// 重新加载设备列表和状态
			_ = LoadAllDevicesAsync();

			// 更新连接状态
			_ = UpdateConnectionStatusAsync();
		}

		/// <summary>
		/// 启动连接状态监控定时任务
		/// </summary>
		private async Task StartConnectionMonitoringAsync()
		{
			try
			{
				// 首次更新连接状态
				await UpdateConnectionStatusAsync();

				// 每5秒检查一次所有设备的连接状态
				_ = Task.Run(async () =>
				{
					while (!_disposed)
					{
						try
						{
							await UpdateConnectionStatusAsync();
							await Task.Delay(TimeSpan.FromSeconds(5));
						}
						catch (Exception ex)
						{
							_logger.LogError(ex, "检查设备连接状态时发生错误");
						}
					}
				});
			}
			catch (Exception ex)
			{
				_logger.LogError(ex, "启动连接状态监控失败");
			}
		}

		/// <summary>
		/// 更新设备连接状态
		/// </summary>
		private async Task UpdateConnectionStatusAsync()
		{
			try
			{
				// 检查连接状态
				await _serialServerManager.CheckConnectionAsync();

				// 在UI线程更新连接状态
				App.Current.Dispatcher.Invoke(() =>
				{
					// 更新TCU连接状态
					if (SelectedTCU != null && SelectedTCU is ITCUBase tcu)
					{
						// 假设TCU使用端口502
						const int tcuPort = 502;
						IsTcuConnected = _serialServerManager.IsPortConnected(tcuPort);
					}

					// 更新油浴锅连接状态
					if (SelectedOilBath != null && SelectedOilBath is IOilBathBase oilBath)
					{
						// 假设油浴锅使用端口503
						const int oilBathPort = 503;
						IsOilBathConnected = _serialServerManager.IsPortConnected(oilBathPort);
					}

					// 更新温度采集模块连接状态
					if (SelectedTemperatureCollector != null && SelectedTemperatureCollector is ITemperatureCollectorBase collector)
					{
						// 假设温度采集模块使用端口504
						const int temperatureCollectorPort = 504;
						IsTemperatureCollectorConnected = _serialServerManager.IsPortConnected(temperatureCollectorPort);
					}

					// 更新切换阀连接状态 - 使用ValveStatus中的IsConnected属性
					if (SelectedValve != null)
					{
						// 优先使用ValveStatus中的连接状态
						IsValveConnected = ValveStatus?.IsConnected ?? false;
					}
				});
			}
			catch (Exception ex)
			{
				_logger.LogError(ex, "更新连接状态失败");
			}
		}

		/// <summary>
		/// 设备状态变化事件处理
		/// </summary>
		private void OnDeviceStatusChanged(object sender, DeviceStatusEventArgs e)
		{
			try
			{
				// 处理TCU状态变化
				if (SelectedTCU != null && e.DeviceId == SelectedTCU.EquipmentId && e.Status is TCUStatus tcuStatus)
				{
					TcuStatus = tcuStatus;
				}
				// 处理油浴锅状态变化
				else if (SelectedOilBath != null && e.DeviceId == SelectedOilBath.EquipmentId && e.Status is OilBathStatus oilBathStatus)
				{
					OilBathStatus = oilBathStatus;
				}
				// 处理温度采集模块状态变化
				else if (SelectedTemperatureCollector != null && e.DeviceId == SelectedTemperatureCollector.EquipmentId && e.Status is TemperatureCollectorStatus tempStatus)
				{
					TemperatureCollectorStatus = tempStatus;
				}
				// 处理切换阀状态变化
				else if (SelectedValve != null && e.DeviceId == SelectedValve.EquipmentId && e.Status is ValveStatus valveStatus)
				{
					ValveStatus = valveStatus;
					IsValveConnected = valveStatus.IsConnected;  // 更新连接状态
					ValveCurrentChannel = valveStatus.CurrentChannel.ToString();  // 更新通道显示
				}
			}
			catch (Exception ex)
			{
				_logger.LogError(ex, "处理设备状态变化事件异常");
			}
		}

		/// <summary>
		/// 加载所有设备
		/// </summary>
		[RelayCommand]
		private async Task LoadAllDevicesAsync()
		{
			try
			{
				IsBusy = true;

				// 加载TCU设备列表
				var tcuList = _deviceManager.TCUs.Values.ToList();
				TcuList = new ObservableCollection<ITCUBase>(tcuList);
				if (TcuList.Count > 0)
				{
					SelectedTCU = TcuList[0];
				}

				// 加载油浴锅设备列表
				var oilBathList = _deviceManager.OilBaths.Values.ToList();
				OilBathList = new ObservableCollection<IOilBathBase>(oilBathList);
				if (OilBathList.Count > 0)
				{
					SelectedOilBath = OilBathList[0];
				}

				// 加载温度采集模块列表
				var temperatureCollectorList = _deviceManager.TemperatureCollectors.Values.ToList();
				TemperatureCollectorList = new ObservableCollection<ITemperatureCollectorBase>(temperatureCollectorList);
				if (TemperatureCollectorList.Count > 0)
				{
					SelectedTemperatureCollector = TemperatureCollectorList[0];
				}

				// 加载切换阀列表
				var valveList = _deviceManager.Valves.Values.ToList();
				ValveList = new ObservableCollection<IValveBase>(valveList);
				if (ValveList.Count > 0)
				{
					SelectedValve = ValveList[0];
				}

				// 更新设备状态
				//await _deviceStatusService.UpdateAllDeviceStatusAsync();

				// 更新连接状态
				await UpdateConnectionStatusAsync();

				ShowOperationResult(true, "设备列表加载完成");
			}
			catch (Exception ex)
			{
				_logger.LogError(ex, "加载设备列表失败");
				ShowOperationResult(false, $"加载设备列表失败: {ex.Message}");
			}
			finally
			{
				IsBusy = false;
			}
		}

		#region TCU操作方法

		/// <summary>
		/// TCU设备选择变更处理
		/// </summary>
		partial void OnSelectedTCUChanged(ITCUBase value)
		{
			if (value != null)
			{
				_ = LoadTCUStatusAsync(value.EquipmentId);
			}
		}

		/// <summary>
		/// 加载TCU状态
		/// </summary>
		[RelayCommand]
		private async Task LoadTCUStatusAsync(string tcuId)
		{
			if (string.IsNullOrEmpty(tcuId))
			{
				TcuStatus = new TCUStatus();
				return;
			}

			try
			{
				IsBusy = true;
				TcuStatus = await _deviceStatusService.GetTCUStatusAsync(tcuId);
				TcuPowerSwitch = TcuStatus.PowerSwitch;
				ShowOperationResult(true, $"已加载TCU {SelectedTCU?.Name} 状态");
			}
			catch (Exception ex)
			{
				_logger.LogError(ex, "加载TCU状态失败");
				ShowOperationResult(false, $"加载TCU状态失败: {ex.Message}");
			}
			finally
			{
				IsBusy = false;
			}
		}

		/// <summary>
		/// 设置TCU温度
		/// </summary>
		[RelayCommand]
		private async Task SetTCUTemperatureAsync()
		{
			if (SelectedTCU == null)
			{
				ShowOperationResult(false, "请先选择TCU设备");
				return;
			}

			try
			{
				IsBusy = true;
				var result = await SelectedTCU.SetTemperatureAsync(TcuSetTemperature);
				if (result.Success)
				{
					ShowOperationResult(true, $"已设置TCU {SelectedTCU.Name} 温度为 {TcuSetTemperature}℃");
					await LoadTCUStatusAsync(SelectedTCU.EquipmentId);
				}
				else
				{
					ShowOperationResult(false, $"设置TCU温度失败: {result.Message}");
				}
			}
			catch (Exception ex)
			{
				_logger.LogError(ex, "设置TCU温度失败");
				ShowOperationResult(false, $"设置TCU温度失败: {ex.Message}");
			}
			finally
			{
				IsBusy = false;
			}
		}

		/// <summary>
		/// TCU电源开关
		/// </summary>
		[RelayCommand]
		private async Task PowerTCUAsync()
		{
			if (SelectedTCU == null)
			{
				ShowOperationResult(false, "请先选择TCU设备");
				return;
			}

			try
			{
				IsBusy = true;
				var result = await SelectedTCU.PowerSwitchAsync(TcuPowerSwitch);
				if (result.Success)
				{
					string status = TcuPowerSwitch ? "开启" : "关闭";
					ShowOperationResult(true, $"已{status}TCU {SelectedTCU.Name} 电源");
					await LoadTCUStatusAsync(SelectedTCU.EquipmentId);
				}
				else
				{
					ShowOperationResult(false, $"操作TCU电源失败: {result.Message}");
				}
			}
			catch (Exception ex)
			{
				_logger.LogError(ex, "操作TCU电源失败");
				ShowOperationResult(false, $"操作TCU电源失败: {ex.Message}");
			}
			finally
			{
				IsBusy = false;
			}
		}

		#endregion

		#region 油浴锅操作方法

		/// <summary>
		/// 油浴锅设备选择变更处理
		/// </summary>
		partial void OnSelectedOilBathChanged(IOilBathBase value)
		{
			if (value != null)
			{
				_ = LoadOilBathStatusAsync(value.EquipmentId);
			}
		}

		/// <summary>
		/// 加载油浴锅状态
		/// </summary>
		[RelayCommand]
		private async Task LoadOilBathStatusAsync(string oilBathId)
		{
			if (string.IsNullOrEmpty(oilBathId))
			{
				OilBathStatus = new OilBathStatus();
				return;
			}

			try
			{
				IsBusy = true;
				OilBathStatus = await _deviceStatusService.GetOilBathStatusAsync(oilBathId);
				OilBathSetTemperature = OilBathStatus.SetTemperatureSV;
				OilBathRunningStatus = OilBathStatus.Mode;
				ShowOperationResult(true, $"已加载油浴锅 {SelectedOilBath?.Name} 状态");
			}
			catch (Exception ex)
			{
				_logger.LogError(ex, "加载油浴锅状态失败");
				ShowOperationResult(false, $"加载油浴锅状态失败: {ex.Message}");
			}
			finally
			{
				IsBusy = false;
			}
		}

		/// <summary>
		/// 设置油浴锅温度
		/// </summary>
		[RelayCommand]
		private async Task SetOilBathTemperatureAsync()
		{
			if (SelectedOilBath == null)
			{
				ShowOperationResult(false, "请先选择油浴锅设备");
				return;
			}

			try
			{
				IsBusy = true;
				var result = await SelectedOilBath.SetTemperatureAsync(OilBathSetTemperature);
				if (result.Success)
				{
					ShowOperationResult(true, $"已设置油浴锅 {SelectedOilBath.Name} 温度为 {OilBathSetTemperature}℃");
					await LoadOilBathStatusAsync(SelectedOilBath.EquipmentId);
				}
				else
				{
					ShowOperationResult(false, $"设置油浴锅温度失败: {result.Message}");
				}
			}
			catch (Exception ex)
			{
				_logger.LogError(ex, "设置油浴锅温度失败");
				ShowOperationResult(false, $"设置油浴锅温度失败: {ex.Message}");
			}
			finally
			{
				IsBusy = false;
			}
		}

		/// <summary>
		/// 设置油浴锅运行状态
		/// </summary>
		[RelayCommand]
		private async Task SetOilBathRunningStatusAsync(object parameter)
		{
			if (SelectedOilBath == null)
			{
				ShowOperationResult(false, "请先选择油浴锅设备");
				return;
			}

			try
			{
				IsBusy = true;
				// 从CommandParameter获取状态值
				int status = 0;
				if (parameter != null && int.TryParse(parameter.ToString(), out int paramValue))
				{
					status = paramValue;
				}

				var result = await SelectedOilBath.SetRunningStatusAsync(status);
				if (result.Success)
				{
					string statusText = status switch
					{
						0 => "运行",
						2 => "停止",
						_ => status.ToString()
					};
					ShowOperationResult(true, $"已设置油浴锅 {SelectedOilBath.Name} 运行状态为 {statusText}");
					await LoadOilBathStatusAsync(SelectedOilBath.EquipmentId);
				}
				else
				{
					ShowOperationResult(false, $"设置油浴锅运行状态失败: {result.Message}");
				}
			}
			catch (Exception ex)
			{
				_logger.LogError(ex, "设置油浴锅运行状态失败");
				ShowOperationResult(false, $"设置油浴锅运行状态失败: {ex.Message}");
			}
			finally
			{
				IsBusy = false;
			}
		}

		#endregion

		#region 温度采集模块操作方法

		/// <summary>
		/// 温度采集模块设备选择变更处理
		/// </summary>
		partial void OnSelectedTemperatureCollectorChanged(ITemperatureCollectorBase value)
		{
			if (value != null)
			{
				_ = LoadTemperatureCollectorStatusAsync(value.EquipmentId);
			}
		}

		/// <summary>
		/// 加载温度采集模块状态
		/// </summary>
		[RelayCommand]
		private async Task LoadTemperatureCollectorStatusAsync(string collectorId)
		{
			if (string.IsNullOrEmpty(collectorId))
			{
				TemperatureCollectorStatus = new TemperatureCollectorStatus();
				return;
			}

			try
			{
				IsBusy = true;
				TemperatureCollectorStatus = await _deviceStatusService.GetTemperatureCollectorStatusAsync(collectorId);
				ShowOperationResult(true, $"已加载温度采集模块 {SelectedTemperatureCollector?.Name} 状态");
			}
			catch (Exception ex)
			{
				_logger.LogError(ex, "加载温度采集模块状态失败");
				ShowOperationResult(false, $"加载温度采集模块状态失败: {ex.Message}");
			}
			finally
			{
				IsBusy = false;
			}
		}

		#endregion

		#region 切换阀操作方法

		/// <summary>
		/// 切换阀设备选择变更处理
		/// </summary>
		partial void OnSelectedValveChanged(IValveBase value)
		{
			if (value != null)
			{
				_ = LoadValveStatusAsync(value.EquipmentId);
			}
			else
			{
				ValveCurrentChannel = "未知";
			}
		}

		/// <summary>
		/// 加载切换阀状态
		/// </summary>
		[RelayCommand]
		private async Task LoadValveStatusAsync(string valveId)
		{
			if (string.IsNullOrEmpty(valveId))
			{
				ValveStatus = new ValveStatus();
				ValveCurrentChannel = "未知";
				IsValveConnected = false;
				return;
			}

			try
			{
				IsBusy = true;
				// 获取阀门整体状态
				ValveStatus = await _deviceStatusService.GetValveStatusAsync(valveId);
				TargetValveChannel = ValveStatus.CurrentChannel;
				IsValveConnected = ValveStatus.IsConnected;  // 更新连接状态

				// 获取当前通道状态
				if (SelectedValve != null)
				{
					var channelResult = await SelectedValve.GetCurrentChannelAsync();
					ValveCurrentChannel = channelResult.ToString();
				}

				ShowOperationResult(true, $"已加载切换阀 {SelectedValve?.Name} 状态，当前通道：{ValveCurrentChannel}");
			}
			catch (Exception ex)
			{
				_logger.LogError(ex, "加载切换阀状态失败");
				ShowOperationResult(false, $"加载切换阀状态失败: {ex.Message}");
				ValveCurrentChannel = "读取失败";
				IsValveConnected = false;  // 出错时设置为未连接
			}
			finally
			{
				IsBusy = false;
			}
		}

		/// <summary>
		/// 切换阀通道切换
		/// </summary>
		[RelayCommand]
		private async Task SwitchValveChannelAsync(object parameter = null)
		{
			if (SelectedValve == null)
			{
				ShowOperationResult(false, "请先选择切换阀设备");
				return;
			}

			// 如果提供了参数，优先使用参数中的通道值
			if (parameter != null && int.TryParse(parameter.ToString(), out int channelParam))
			{
				TargetValveChannel = channelParam;
			}

			// 验证通道值
			if (TargetValveChannel < 0 || TargetValveChannel > 6)
			{
				ShowOperationResult(false, "切换阀通道值无效，有效范围为0-6");
				return;
			}

			try
			{
				IsBusy = true;
				var result = await SelectedValve.SwitchToChannelAndWaitAsync(TargetValveChannel);
				if (result.Success)
				{
					ShowOperationResult(true, $"已切换阀门 {SelectedValve.Name} 到通道 {TargetValveChannel}");
					await LoadValveStatusAsync(SelectedValve.EquipmentId);
				}
				else
				{
					ShowOperationResult(false, $"切换阀通道失败: {result.Message}");
				}
			}
			catch (Exception ex)
			{
				_logger.LogError(ex, "切换阀通道失败");
				ShowOperationResult(false, $"切换阀通道失败: {ex.Message}");
			}
			finally
			{
				IsBusy = false;
			}
		}

		/// <summary>
		/// 复位切换阀
		/// </summary>
		[RelayCommand]
		private async Task ResetValveAsync()
		{
			if (SelectedValve == null)
			{
				ShowOperationResult(false, "请先选择切换阀设备");
				return;
			}

			try
			{
				IsBusy = true;
				var result = await SelectedValve.ResetAsync();
				if (result.Success)
				{
					ShowOperationResult(true, $"已复位切换阀 {SelectedValve.Name}");
					await LoadValveStatusAsync(SelectedValve.EquipmentId);
				}
				else
				{
					ShowOperationResult(false, $"复位切换阀失败: {result.Message}");
				}
			}
			catch (Exception ex)
			{
				_logger.LogError(ex, "复位切换阀失败");
				ShowOperationResult(false, $"复位切换阀失败: {ex.Message}");
			}
			finally
			{
				IsBusy = false;
			}
		}

		#endregion

		/// <summary>
		/// 显示操作结果
		/// </summary>
		private void ShowOperationResult(bool success, string message)
		{
			OperationMessage = message;
			IsOperationSuccess = success;
			ResultMessageColor = success ? Brushes.Green : Brushes.Red;
		}

		/// <summary>
		/// 释放资源
		/// </summary>
		public void Dispose()
		{
			Dispose(true);
			GC.SuppressFinalize(this);
		}

		/// <summary>
		/// 释放资源
		/// </summary>
		/// <param name="disposing">是否为显式释放</param>
		protected virtual void Dispose(bool disposing)
		{
			if (_disposed) return;

			if (disposing)
			{
				// 取消订阅设备状态变化事件
				if (_deviceStatusService != null)
				{
					_deviceStatusService.DeviceStatusChanged -= OnDeviceStatusChanged;
					_logger?.LogInformation("SerialDevicesListViewModel已取消订阅DeviceStatusChanged事件");
				}
			}

			_disposed = true;
		}
	}
}